<?php
/**
 * @copyright	Copyright (C) 2008 Bideew. All rights reserved.
 * @license		GNU/GPL
* This file is part of Bideew.

* Bideew is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.

* Bideew is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with Bideew; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

function autoInclude($type) {
	if(!file_exists(PATHTOROOT.DS."Cache".DS.$type.".php")) {
		createCache($type);
	}
	$lesItems = readCache($type);
	if ($type != "Themes") {includer($lesItems,$type);}
	else {return $lesItems;}
}

function createCache($type) { //$type = Functions, Classes ou Themes
	$pointeur=opendir(PATHTOROOT.$type);
	switch ($type) {
		case "Classes":
		    $type_verif = "class.php";
		break;
		case "Themes":
		    $type_verif = "css";
		break;
		case "Functions":
		    $type_verif = "functions.php";
		break;
	}
	if ($type == "Themes") {
		$pointeur=opendir(PATHTOROOT.'Themes');
		while ($unItem = readdir($pointeur)) {
			if (file_exists(PATHTOROOT.'Themes'.DS.$unItem.DS.$unItem.'.css')) {
				$lesItems[] = $unItem;
			}
		}	
	}
	else {
		while ($unItem = readdir($pointeur)) {
			if (eregi(".$type_verif$", $unItem)) {
				$lesItems[] = $unItem;
			}
		}
	}
	writeCache($type,$lesItems);
}

function writeCache($type,$lesItems) {
	$Pfichier = fopen(PATHTOROOT."Cache".DS.$type.".php", 'w');
	$buffer = "<?php ";
	$buffer .= '$ar  = array(';
	foreach($lesItems as $item) {
		$buffer .= "'$item',";
	}
	$buffer = substr($buffer, 0, -1); // supprime la derniere virgule
	$buffer .= ");";
	$buffer .= " ?>";
	fwrite($Pfichier, $buffer);
	//closedir($Pfichier);
}

function readCache($type) {
	include (PATHTOROOT."Cache".DS.$type.".php");
	return $ar; //Array contenant les items lus
}

function includer($lesItems,$type) {
	foreach ($lesItems as $item) {
		require_once PATHTOROOT.DS.$type.DS.$item;
	}
}
